require 'spider'
class Shop < ActiveRecord::Base
  validates_uniqueness_of :name, :shop_hash, :shop_id, :message => '店铺重复', :allow_nil => true
  validates_presence_of :name, :message => '店铺名不允许为空'

  has_and_belongs_to_many :categories, :join_table => "categories_shops", :foreign_key => "shop_id"
  belongs_to :province, :class_name => 'Area', :foreign_key => 'province_id'
  belongs_to :city, :class_name => 'Area', :foreign_key => 'city_id'
  belongs_to :category #一级分类
  has_many :merchandises

  named_scope :money, :conditions => "prom_url is not null and prom_url <> 'bad'"
  named_scope :osales, :order => "total_sales DESC"
  named_scope :ofans, :order => "fan_num DESC"

  acts_as_taggable
  paginates_per 15
  include Spider

  #TODO 注意验证域名是否更换了
  def domain_url
    domain && "http://#{domain}.tmall.com"
  end

  #前台显示用
  def shop_link
    if domain_url.nil?
      url
    else 
      domain_url
    end
  end

  def logo_link
    if logo.nil?
      '/images/default_logo.jpg'
    else
      logo
    end
  end

  def prom_link
    if prom_url.nil? || prom_url == 'bad'
      nil
    else
      prom_url
    end
  end

  def user_rate_url
    "http://rate.taobao.com/user-rate-#{shop_hash}.htm"
  end
  
  def shuo_url
    "http://shuo.taobao.com/shop#{shop_id}"
  end

  def all_code_url
    "http://www.alimama.com/union/promotion/allCode.htm?pid=#{user_id}"
  end

  def shop_detail_url
    "http://www.alimama.com/union/promotion/shopDetail.htm?oid=#{user_id}"
  end

  def description
    describe || "#{name}的淘宝旗舰店暂时没有描述."
  end

  def meta_desc
    describe.nil? ? "#{name},淘宝商城品牌旗舰店" : "#{describe.mb_chars[0..99]},#{name}淘宝旗舰店"
  end

  def self.hot_tags(num = 50)
    self.tag_counts(:order => 'count DESC', :limit => num)
  end

  def self.create_for_cat(cat_url)
    doc = open_page(cat_url)
    if doc.nil?
      Rails.logger.warn "从分类页抓取商城出错， url: #{cat_url}"
      nil
    else
      shop_htmls = doc.css("div#J-listContainer div.show-hd")
      if shop_htmls.blank?
        Rails.logger.warn "抓取或解析从分类页到商城出错， url:#{cat_url}"
      else
        shop_htmls.each do |shop_html|
          flagship = shop_html.css('h3.show-title span.icon-flagship')
          if flagship.present?
            shop = Shop.new
            shop_a = shop_html.css('h3 span.J_CurrentSellerNick a').first
            shop.name = shop_a.text.strip
            shop.url = shop_a['href']
            shop.shop_hash = shop.url.scan(/view_shop-(\w+)\.htm/).to_s
            shop.shop_id = shop_a['onclick'].scan(/atpanelClick.+,.*\'(\d+)\'.*,.+,.+,.+,.+/).to_s
            citys = shop_html.css('ul.user-info li.city').text.split.map{|s|strip_nbsp s }
            if citys.size == 1
              shop.province = Area.find_by_name citys.first
            elsif citys.size > 1
              shop.province = Area.find_by_name citys.first
              shop.city = Area.find_by_name citys[1]
            end
            shop.save! rescue Rails.logger.info "商城名重复,shop_name: #{shop.name}"
          end
        end
      end

      #有下一页返回下一页
      next_page = doc.css('a.page-next')
      if next_page.blank?
        nil
      else
        Rails.logger.info "下一页: #{next_page.first['href']}"
        next_page.first['href']
      end
    end
  end

  def update_for_user_rate()
    rate_url = user_rate_url
    doc = open_page(rate_url)
    if doc.nil?
      Rails.logger.warn "采集用户购买心得评价页出错, url:#{rate_url}"
    else
      shop_title = doc.css('h3.shop-title')
      if shop_title.blank?
        Rails.logger.warn "抓取或解析评价页出错, url:#{rate_url}"
      else
        uatts = {}
        uatts[:domain] = shop_title.css('a').first['href'].scan(/http:\/\/(.+)\.tmall\.com/).to_s
        uatts[:company_name] = strip_nbsp(doc.css('div.fleft2').first.text)
        category_name = strip_nbsp(doc.css('div.left-box div.bd ul').first.css('a').text)
        category = Category.find_by_name(category_name)
        uatts[:category_id] = category.id unless category.nil?
        province = nil
        city = nil
        if province_id.nil?
          area = doc.css('li.locus').first.children.last.text[1..-2].split(',').map{|s|s.strip}
          province = Area.find_by_name area.first
          uatts[:province_id] = province.id if province
          (city = Area.find_by_name area[1]) && (uatts[:city_id] = city.id) if area.size > 1
        end
        div_total = doc.css('div.total')
        uatts[:total_sales] = div_total.first.css('span').last.text.to_i if div_total.present? #用户刚开店,评价有可能为空 http://rate.taobao.com/user-rate-6b495bc692b2aa9ce2e0c894866be7ca.htm
        Shop.update(id, uatts)
      end
    end
  end

  def update_for_shuo
    rate_url = shuo_url
    doc = open_page(rate_url)
    if doc.nil?
      Rails.logger.warn "采集掌柜说页出错, url:#{rate_url}"
    else
      fans_num = doc.css('span.fans-num').text
      if fans_num.blank?
        Rails.logger.warn "抓取或解析掌柜说出错, url:#{rate_url}"
      else
        uatts = {}
        uatts[:fan_num] = fans_num
        #TODO 暂不更新
        #logo_url = doc.css('div.mshop-pic img').first['src']
        #unless (/shop-logo/ =~ logo_url).nil?  #有shop-logo才代表有logo
        #  # 应该先放到tmp目录,根据file改后缀名,如果格式不对,则不保存
        #  logo_path = "/images/shop_logo/#{SecureRandom.hex}.jpg"
        #  %x(wget #{logo_url} -O #{Rails.root}/public#{logo_path})
        #  uatts[:logo] = logo_path
        #end
        uatts[:user_id] = doc.css('div.mshop-intro a').first['href'].scan(/n=(\d+)/).to_s
        desc_text = doc.css('p.describe').text
        uatts[:describe] = desc_text if desc_text.present?
        Shop.update(id, uatts)
        tags_text = doc.css('div.mshop-panel div.mshop-box')[2].css('p').text
        self.tag_list = tags_text if tags_text.present?
        cat_names = doc.css('div.mshop-panel div.mshop-box-border div.mshop-box')[0].css('p').text.split(';')
        if cat_names.size > 0
          #判断是否二级分类
          cat_names.each do |cat_name|
            cat2 = Category.find_by_name cat_name
            self.categories << cat2 if cat2.present? && cat2.level == 2 && !self.categories.include?(cat2)
          end
        end
        self.save!
      end
    end
  end
end
